<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="注册 / 登录"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 登录表单 -->
    <van-form 
      :show-error="false"
      :show-error-message="false"
      ref="login-form"
      @submit="onLogin"
      @failed="onFailed"
      >
      <van-field
        v-model="user.mobile"
        clearable
        icon-prefix="toutiao"
        name="mobile"
        left-icon="shouji"
        placeholder="请输入手机号"
        :rules="formRules.mobile"
      />
      <van-field
        v-model="user.code"
        clearable
        center
        icon-prefix="toutiao"
        name="code"
        left-icon="yanzhengma"
        placeholder="请输入认证码"
        :rules="formRules.code"
      >
        <template #button>
          <van-count-down 
            v-if="isCountDownShow"
            :time="1000 * 60" 
            format="ss s"
            @finish="isCountDownShow = false"
          />
          <van-button 
            v-else
            size="small" 
            round
            center
            class="send-btn"
            :loading="isSendSmsLoading"
            @click.prevent="onSendSms"
          >发送验证码</van-button>
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button type="info" block class="login-btn" >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from '@/api/user'
// import {Toast} from 'vant'

export default {
  name: 'Index',
  components: {},
  props: {},
  data () {
    return {
      isCountDownShow: false,
      isSendSmsLoading: false,
      user: {
        mobile: '13911111111',
        code: '246810'
      },
      formRules: {
        mobile: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '手机号格式错误' },
        ],
        code: [
          { required: true, message: '请输入验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式错误' },
        ], 
      }
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onLogin() {
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true,
        duration: 0  //值为0时不会消失，除非进行清除clear或者出现新的
      });
      try {
        const { data } = await login(this.user)
        // console.log(res);

        //处理登录后结果
        this.$toast.success('登录成功')

        //将后端返回的用户状态（token等数据）放到Vuex容器中
        this.$store.commit('setUser', data.data)

        // 清除 layout 的缓存，让它重新渲染
        this.$store.commit('removeCachePage', 'LayoutIndex')

        //登录成功后跳回my页面
        
        this.$router.push(this.$route.query.redirect || '/')
        //目前不推荐使用这种方法
      } catch(err) {
        this.$toast.fail('登陆失败,手机号码或者验证码');
      }
    },

    onFailed(error) {
      if(error.errors[0]) {
        this.$toast({
          message: error.errors[0].message,
          position: top
        })
      }
    },

    async onSendSms() {
      try {
        //校验手机验证码
        await this.$refs["login-form"].validate('mobile')

        //发送验证码就显示loading
        this.isSendSmsLoading = true

        //验证通过，请求发送验证码
        await sendSms(this.user.mobile)

        //短信发出去，隐藏发送按钮，显示倒计时
        this.isCountDownShow = true

      } catch(err) {
        //有错误就会进入catch
        //不同的错误需要不同的提示，那需要进行判断
        let message = ''
        if(err && err.response && err.response.status === 429){
          //发送验证码错误
          message = '发送太频繁了，请稍后再试'
        }else if(err.name === 'mobile') {
          //表单验证错误
          message = err.message
        }else {
          //出现其他的错误
          message = '发送失败，请稍后重试'
        }

        //提示用户
        this.$toast({
          message,
          position: top
        })
      }

      //关闭loading
      this.isSendSmsLoading = false
    }
  }
}
</script>

<style scoped lang="less">
  .login-container {
    .send-btn {
      width: 78px;
      height: 23px;
      background-color: #ededed;
      .van-button__text {
        font-size: 10px;
        color: #666666;
      }
    }
    .login-btn-wrap {
      padding: 26px 16px;
      .login-btn {
        background-color: #6db4fb;
        border: none;
        .login-btn__text {
          font-size: 15px;
        }
      }
    }
  }
</style>